package others;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import models.Submission;

public class DumbFS extends SubmissionsRepository {

	private DumbFS () {
	}

	private static DumbFS _instance;

	public static SubmissionsRepository getInstance() {
		if (_instance == null) {
			_instance = new DumbFS();
		}
		return _instance;
	}

	public File getSubmission(byte[] key) {
		return new File(new String(key));
	}

	public byte[] getSubmissionKey(Submission submission) {
		String submissionZipName = submission.student.studentID + "_" + submission.assignment.toString() + "_" + submission.id + ".zip";
		// System.out.println("Key: " + submissionZipName);
		// return _.toByteArray(submission.id)
		return submissionZipName.getBytes();
	}

	public void saveSubmission(byte[] key, File file) {
		byte[] buf = new byte[1024];
		String submissionZipName = new String(key);
		System.out.println("--> " + submissionZipName);
		if (file.getName().endsWith(".zip")) {
			try {
				FileOutputStream out = new FileOutputStream(submissionZipName);
				FileInputStream in = new FileInputStream(file);
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				in.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				ZipOutputStream out = new ZipOutputStream(new FileOutputStream(submissionZipName));
				FileInputStream in = new FileInputStream(file);
				out.putNextEntry(new ZipEntry(file.getName()));
				int len;
				while ((len = in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.closeEntry();
				in.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}